package dnl.dev.memlog;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.Set;

import org.apache.commons.io.FileUtils;

import dnl.dev.memlog.parser.ClassInstanceCount;
import dnl.dev.memlog.parser.HistogramParser;
import dnl.dev.memlog.parser.HistogramsDir;
import dnl.dev.memlog.sampler.MemSampler;
import dnl.util.ui.ProgressListener;

public class MemlogContext {

	public static enum SamplingStatus {
		SUCCESS, ERR_SAMPLE_NAME_EXISTS
	};

	private HistogramParser histogramParser;
	private MemlogProject memlogProject;
	private HistogramsDir histogramsDir;
	private MemSampler memSampler;

	public MemlogContext(MemlogProject memlogProject) {
		this.memlogProject = memlogProject;
	}

	public MemlogProject getMemlogProject() {
		return memlogProject;
	}

	public Date getFileCreationDate(String filename) {
		return memlogProject.getFileCreationDate(filename);
	}

	public int getNumberOfHistograms() {
		return histogramsDir.listHistogramFileNames().length;
	}

	public String getHistogramsDirName() {
		return memlogProject.getProjectDirPath();
	}

	public Set<String> getClassNames() {
		return histogramParser.getClassNames();
	}

	public List<ClassInstanceCount> getStats(String className) {
		return histogramParser.getStats(className);
	}

	public boolean isDataPrepared() {
		return histogramParser != null;
	}

	public MemSampler getMemSampler() {
		return memSampler;
	}

	public void setMemSampler(MemSampler memSampler) {
		this.memSampler = memSampler;
	}

	public HistogramsDir getHistogramsDir() {
		if (histogramsDir == null) {
			histogramsDir = new HistogramsDir(memlogProject.getProjectDir());
		}
		return histogramsDir;
	}

	public void deleteSnapshot(String name) {
		File histogramFile = histogramsDir.getHistogramFile(name);
		if (histogramFile.exists()) {
			try {
				FileUtils.forceDelete(histogramFile);
			} catch (IOException e) {
				e.printStackTrace();
			}
			if (histogramParser != null) {
				histogramParser.deleteHistogramFile(histogramFile);
			}
		}
	}

	public SamplingStatus takeSample(String name) {
		File histogramFile = histogramsDir.getHistogramFile(name);
		if (histogramFile.exists()) {
			return SamplingStatus.ERR_SAMPLE_NAME_EXISTS;
		}
		memSampler.takeSample(name);
		if (histogramParser != null) {
			histogramParser.addHistogramFile(histogramFile);
		}
		return SamplingStatus.SUCCESS;
	}

	public void prepareData(ProgressListener progressListener) {
		if (histogramParser == null) {
			histogramParser = new HistogramParser(memlogProject);
			histogramParser.parse(getHistogramsDir(), progressListener);
		}
	}
}
